package com.pkx.guide.info.service.impl;

import com.pkx.guide.info.service.SocketService;
import org.springframework.stereotype.Service;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * socket业务类
 */
@Service
public class SocketServiceImpl implements SocketService {

    @Override
    public Socket clientSocket(String host, Integer port) {
        Socket socket = new Socket();
        SocketAddress endpoint = new InetSocketAddress(host, port);
        try {
            socket.connect(endpoint, 3000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return socket;
    }

    @Override
    public void send(byte[] bytes,Socket socket) {
        try {
            DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
            outputStream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public byte[] receive(Socket socket) {
        try {
            DataInputStream inputStream = new DataInputStream(socket.getInputStream());
            byte[] bytes = new byte[1024];
            inputStream.read(bytes);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
